package cn.shop.admin.controller;

import cn.dev33.satoken.annotation.SaCheckRole;
import cn.dev33.satoken.session.SaSession;
import cn.dev33.satoken.session.SaSessionCustomUtil;
import cn.hutool.core.util.RandomUtil;
import cn.shop.admin.common.util.CurrentUserUtil;
import cn.shop.admin.entity.backRoleModule.BackRole;
import cn.shop.admin.entity.backUserModule.AdminMenuVO;
import cn.shop.admin.entity.backUserModule.BackUser;
import cn.shop.admin.entity.backUserModule.TransactionPasswordReq;
import cn.shop.admin.req.AssignRoleReq;
import cn.shop.admin.service.BackRoleService;
import cn.shop.admin.service.BackUserService;
import cn.shop.base.MyPage;
import cn.shop.thiredparty.entity.SmsSendResult;
import cn.shop.thiredparty.entity.SmsSendStatus;
import cn.shop.thiredparty.service.ThiredpartyService;
import cn.shop.utils.ApiResult;
import cn.shop.utils.annotation.OperationLog;
import cn.shop.utils.constant.Constant;
import cn.shop.utils.constant.SMSVerificationCode;
import cn.shop.utils.enums.OperationType;
import cn.shop.validation.Save;
import cn.shop.validation.Update;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.extern.slf4j.Slf4j;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PatchMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.constraints.NotNull;
import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * 总后台角色表(BackUser)表控制层
 *
 * @author jzw
 * @since 2021-11-02 11:35:13
 */
@Validated
@RestController
@RequestMapping("/api/v1/backUser")
@Slf4j
public class BackUserController {

	/**
	 * 服务对象
	 */
	@Resource
	private BackUserService backUserService;

	@Resource
	private ThiredpartyService thiredpartyService;

	/**
	 * 服务对象
	 */
	@Resource
	private BackRoleService roleService;

	@PutMapping("disOrEnaAccount")
	@OperationLog(module = "账户表模块", type = OperationType.UPDATE, desc = "启禁用账户")
	public ApiResult<Map<String, Object>> disOrEnaAccount(@NotNull(message = "账号id不能为空") Long accountId) {
		return ApiResult.result(backUserService.disOrEnaAccount(accountId));
	}

	/**
	 * 获取全部内置账户id
	 *
	 * @author jy
	 * @since 2020-07-15 14:50:59
	 */
	@GetMapping("/listInitAccount")
	public ApiResult<List<Object>> listInitAccount() {
		LambdaQueryWrapper<BackUser> queryWrapper = Wrappers.lambdaQuery();
		queryWrapper.eq(BackUser::getInitial, true).eq(BackUser::getEnable, true);
		queryWrapper.select(BackUser::getId);
		return ApiResult.success(backUserService.listObjs(queryWrapper));
	}

	/**
	 * @return
	 * @author jy
	 * @since 2020-07-15 14:50:59
	 */
	@PutMapping("/setInitAccount")
	@OperationLog(module = "账户表模块", type = OperationType.UPDATE, desc = "批量设置内置账户")
	public ApiResult<Map<String, Object>> setInitAccount(@RequestBody List<Long> idList) {
		return ApiResult.result(backUserService.setInitAccount(idList));
	}

	/**
	 * 查询当前登录人信息
	 *
	 * @author jy
	 * @since 2022/1/18 10:47
	 */
	@GetMapping("/userInfo")
	public ApiResult<BackUser> userInfo() {
		BackUser user = backUserService.getById(CurrentUserUtil.getUserId());
		List<Long> list = roleService.getRoleByUserId(user.getId());
		List<BackRole> roles = roleService.listByIds(list);
		user.setRoles(roles);
		return ApiResult.success(user);
	}

	/**
	 * 获取当前登录人菜单
	 *
	 * @author jy
	 * @since 2022/1/18 10:47
	 */
	@GetMapping("menu")
	public ApiResult<List<AdminMenuVO>> getMenuList() {
		return ApiResult.success(backUserService.getMenuList());
	}


	/**
	 * 分页查询所有数据
	 *
	 * @param page     分页对象
	 * @param backUser 查询实体
	 * @return 所有数据
	 */
	@GetMapping("queryByPage")
	public ApiResult<MyPage<BackUser>> queryByPage(MyPage<BackUser> page, BackUser backUser,
	                                               @RequestParam(required = false) @DateTimeFormat(pattern = Constant.DATETIME_FORMAT) LocalDateTime startTime,
	                                               @RequestParam(required = false) @DateTimeFormat(pattern = Constant.DATETIME_FORMAT) LocalDateTime endTime) {
		return ApiResult.success(backUserService.page(page, Wrappers.lambdaQuery(backUser)
				.apply(startTime != null,
						"date_format (create_time,'%Y-%m-%d %H:%i') >= date_format ({0},'%Y-%m-%d %H:%i')", startTime)
				.apply(endTime != null,
						"date_format (create_time,'%Y-%m-%d %H:%i') <= date_format ({0},'%Y-%m-%d %H:%i')", endTime)));
	}

	/**
	 * 通过主键查询单条数据
	 *
	 * @param id 主键
	 * @return 单条数据
	 */
	@GetMapping("queryOneById/{id}")
	public ApiResult<BackUser> selectOneById(@PathVariable Serializable id) {
		return ApiResult.success(backUserService.getById(id));
	}


	/**
	 * 分配角色
	 *
	 * @param assignRoleReq 实体对象
	 * @return 新增结果
	 */
	@PostMapping("assignRole")
	public ApiResult<Map<String, Object>> assignRole(@Validated @RequestBody AssignRoleReq assignRoleReq) {
		return ApiResult.result(roleService.assignRole(assignRoleReq));
	}

	/**
	 * 查询所有数据
	 *
	 * @param user 查询实体
	 * @return 所有数据
	 * @author jy
	 * @since 2022-01-17 12:08:46
	 */
	@GetMapping("queryAll")
	public ApiResult<List<BackUser>> queryAll(BackUser user) {
		user.setEnable(true);
		return ApiResult.success(backUserService.list(new QueryWrapper<>(user)));
	}

	/**
	 * 新增数据
	 *
	 * @param backUser 实体对象
	 * @return 新增结果
	 */
	@PostMapping("insert")
	@OperationLog(desc = "新增用户", type = OperationType.CREATE)
	public ApiResult<Map<String, Object>> insert(@Validated(Save.class) @RequestBody BackUser backUser) {
		return ApiResult.result(backUserService.insert(backUser));
	}

	/**
	 * 修改数据
	 *
	 * @param backUser 实体对象
	 * @return 修改结果
	 */
	@PutMapping("update")
	@OperationLog(desc = "修改用户", type = OperationType.UPDATE)
	public ApiResult<Map<String, Object>> update(@Validated(Update.class) @RequestBody BackUser backUser) {
		return ApiResult.result(backUserService.update(backUser));
	}

	/**
	 * 设置交易密码
	 *
	 * @return 修改结果
	 */
	@GetMapping("getTPCode")
	public ApiResult<Map<String, Object>> getTransactionPasswordCode(@RequestParam String phone) {
		String code = RandomUtil.randomNumbers(6);

		SmsSendResult result = thiredpartyService.sendSms(code, 5, phone);
		if (result != null && result.getStatus() == SmsSendStatus.OK) {
			SaSession session = SaSessionCustomUtil.getSessionById(SMSVerificationCode.TRANSACTION_PASSWORD_KEY + phone);
			session.set("code", code);
			session.updateTimeout(300);
			return ApiResult.success("验证码发送成功");
		}
		else {
			return ApiResult.fail("验证码发送失败");
		}
	}

	/**
	 * 设置交易密码
	 *
	 * @return 修改结果
	 */
	@PutMapping("setTransactionPassword")
	@SaCheckRole("ROOTUSER")
	@OperationLog(desc = "设置交易密码", type = OperationType.UPDATE)
	public ApiResult<Map<String, Object>> setTransactionPassword(@Validated @RequestBody TransactionPasswordReq transactionPasswordReq) {
		return ApiResult.result(backUserService.setTransactionPassword(transactionPasswordReq));
	}


	/**
	 * 删除单条数据
	 *
	 * @param id 主键
	 * @return 删除结果
	 */
	@DeleteMapping("delete/{id}")
	public ApiResult<Map<String, Object>> delete(@PathVariable Long id) {
		BackUser user = new BackUser();
		LambdaUpdateWrapper<BackUser> updateWrapper = Wrappers.lambdaUpdate();
		updateWrapper.eq(BackUser::getId, id).eq(BackUser::getInitial, false);
		return ApiResult.result(backUserService.deleteWithFill(user, updateWrapper));
	}

	/**
	 * 批量删除数据
	 *
	 * @param idList 主键结合
	 * @return 删除结果
	 */
	@DeleteMapping("batchDelete")
	public ApiResult<Map<String, Object>> batchDelete(@RequestParam("idList") List<Long> idList) {
		BackUser user = new BackUser();
		user.setInitial(false);
		return ApiResult.result(backUserService.batchDelete(idList, user));

	}

}

